package com.fenghongzhang.lib_common.mmkv


import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 *@author Wcj
 *@description 代理类
 *@date 2022/6/27 14:58
 */
class MMKVProperty<T>(private val defValue: T) : ReadWriteProperty<MMKVOwner, T> {

    override fun getValue(thisRef: MMKVOwner, property: KProperty<*>): T {
        return thisRef.mmkv.run {
            when (defValue) {
                is String -> getString(property.name, defValue)
                is Boolean -> getBoolean(property.name, defValue)
                is Long -> getLong(property.name, defValue)
                is Int -> getInt(property.name, defValue)
                is Float -> getFloat(property.name, defValue)
                is Double -> decodeDouble(property.name, defValue)
                else -> Unit
            }
        } as T
    }

    /**
     * thisRef  对象的引用
     * property 对象的属性,比如name等.类型等
     * value 具体的值
     */
    override fun setValue(thisRef: MMKVOwner, property: KProperty<*>, value: T) {//false
        thisRef.mmkv.run {
            when (value) {
                is String -> putString(property.name, value)
                is Boolean -> putBoolean(property.name, value)//false
                is Long -> putLong(property.name, value)
                is Int -> putInt(property.name, value)
                is Float -> putFloat(property.name, value)
                is Double -> encode(property.name, value)
                else -> Unit
            }
        }
    }

}
